package com.fanyouzhao.ehome2.admin.controller;


import com.fanyouzhao.ehome2.admin.exception.BusinessException;
import com.fanyouzhao.ehome2.core.util.JsonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: fanyouzhao
 * @date: 16:58 2021/6/1
 */
@Controller
@ControllerAdvice
@Log4j2
public class ExceptionController {

    @ExceptionHandler({Throwable.class})
    @ResponseBody
    public JsonResult throwableHandler(Exception e){
        JsonResult jsonResult = new JsonResult();

        if (e instanceof BusinessException){
            // 向前端返回消息
            jsonResult.setCode("0");
            jsonResult.setMsg(e.getMessage());
        }else {
            // 把系统异常记录日志，同时向前端返回500状态码
            jsonResult.setCode("500");
            jsonResult.setMsg("服务器开小差了,请稍后再试");

            log.info("-----------------begin-----------------------"); //分割线方便阅读
            log.info(e);  // 先记录异常对象的toString状态: 包括异常类型和异常原因
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                log.info(stackTraceElement);
            }
            log.info("-------------------end---------------------");//分割线方便阅读
        }
        return jsonResult;
    }
}